/**
 * 
 */
package com.risetek.tft.utils.hibernate.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

import com.alibaba.fastjson.JSONObject;

/**
 * @author  
 * 
 */
public class CustomerJsonTypeOfMap implements UserType, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Class returnedClass = Map.class; // 属性的java类型
	private static final int[] SQL_TYPES = new int[] { Types.VARCHAR }; // 数据库中类型

	public Object assemble(Serializable cached, Object owner)
			throws HibernateException {
		return cached;
	}

	public Object deepCopy(Object value) throws HibernateException {
		Map sourcelist = (Map) value;
        Map targetMap = new HashMap();
        targetMap.putAll(sourcelist);
        return targetMap;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	public boolean equals(Object arg0, Object arg1) throws HibernateException {
		if (arg0 != null && arg1 != null) {
			return arg0.equals(arg1);
		}
		return false;
	}

	public int hashCode(Object value) throws HibernateException {
		return value.hashCode();
	}

	public boolean isMutable() {
		return false;
	}

	public Object nullSafeGet(ResultSet rs, String[] names,Object arg2)
			throws HibernateException, SQLException {
		String value = rs.getString(names[0]);
		if (StringUtils.isEmpty(value)) {
			return new HashMap();
		}
		JSONObject jsonObject = JSONObject.parseObject(value);
		return (Map)JSONObject.toJavaObject(jsonObject, Map.class);
	}

	public void nullSafeSet(PreparedStatement stmt, Object value, int index )
			throws HibernateException, SQLException {
		if (null == value) {
			stmt.setNull(index, Types.VARCHAR);
			return;
		}
		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(value);
		stmt.setObject(index, jsonObject.toString());
	}

	public Object replace(Object arg0, Object arg1, Object arg2)
			throws HibernateException {
		return arg0;
	}

	public Class returnedClass() {
		return returnedClass;
	}

	public int[] sqlTypes() {
		return SQL_TYPES;
	}

  

}
